/*
 * 文件名：ReworkExamController.java
 * 版权：Copyright by www.infopub.top
 * 描述：
 * 修改人：wuzhiyang
 * 修改时间：2020年3月27日
 * 跟踪单号：
 * 修改单号：
 * 修改内容：
 */

package top.infopub.mgr.ic.web;


import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import top.infopub.mgr.common.page.ParamPage;
import top.infopub.mgr.common.vo.ErrorCodeEnum;
import top.infopub.mgr.common.vo.RspVo;
import top.infopub.mgr.flow.web.GenericFlowController;
import top.infopub.mgr.hr.service.StaffInfoService;
import top.infopub.mgr.ic.domain.BuildInfoDomain;
import top.infopub.mgr.ic.domain.ReworkExamAssist;
import top.infopub.mgr.ic.domain.ReworkExamDomain;
import top.infopub.mgr.ic.service.BuildInfoService;
import top.infopub.mgr.ic.service.ReworkExamService;
import top.infopub.mgr.ic.service.StartBuildService;
import top.infopub.mgr.ic.service.StopBuildService;
import top.infopub.mgr.ic.vo.ReworkExamVo;
import top.infopub.mgr.ic.vo.StopBuildVo;
import top.infopub.mgr.util.FileHelper;
import top.infopub.mgr.util.LogUtil;
import top.infopub.mgr.util.LogUtil.AcctionType;
import top.infopub.mgr.util.LogUtil.LogModelType;
import top.infopub.model.hr.StaffInfo;
import top.infopub.model.ic.BuildInfo;
import top.infopub.model.ic.ReworkExamAtt;
import top.infopub.model.ic.StartBuild;
import top.infopub.model.ic.StopBuild;
import top.infopub.security.util.SessionUserUtils;
import top.infopub.security.vo.AuthorizationVO;
import top.infopub.tdp.sys.service.CodeGeneratorConfigService;
import top.infopub.util.IdFactory;

import com.github.pagehelper.Page;
import com.google.common.collect.Maps;


/**
 * 复工审批表
 * @author WuZhiyang
 * @version 2020年3月27日
 * @see ReworkExamController
 * @since
 */
@Controller
@RequestMapping("/reworkExam")
public class ReworkExamController extends GenericFlowController {

    @Autowired
    private CodeGeneratorConfigService codeGeneratorConfigService;

    @Autowired
    private StaffInfoService staffInfoService;

    @Autowired
    private StopBuildService stopBuildService;

    @Autowired
    private StartBuildService startBuildService;

    @Autowired
    private BuildInfoService buildInfoService;

    @Autowired
    private ReworkExamService reworkExamService;

    /**
     * 复工审批表
     * @return
     */
    @RequestMapping("/list")
    public String list() {
        return "ic/lay-reworkExam-list";
    }

    /**
     * 停工审批列表数据
     * @return
     */
    @RequestMapping("/queryDataByCondition")
    @ResponseBody
    public RspVo<ReworkExamDomain> queryDataByCondition(ReworkExamVo reworkExamVo,
                                                        ParamPage paramPage) {
        Page<ReworkExamDomain> page = new Page<ReworkExamDomain>();
        page.setPageNum(paramPage.getPage());
        page.setPageSize(paramPage.getLimit());
        //查询时，结束日期增加一天
        if (reworkExamVo.getEndDate() != null) {
            reworkExamVo.setEndDate(DateUtils.addDays(reworkExamVo.getEndDate(), 1));
        }
        //查询时，结束日期增加一天
        if (reworkExamVo.getPlanEndDate() != null) {
            reworkExamVo.setPlanEndDate(DateUtils.addDays(reworkExamVo.getPlanEndDate(), 1));
        }
        page = reworkExamService.selectByDomainWhere(page, reworkExamVo);
        return RspVo.getSuccessResponse(page.getTotal(), page.getResult());
    }

    /**
     * 停工审批-我审批的列表数据
     * @return
     */
    @RequestMapping("/queryMyCheckDataByCondition")
    @ResponseBody
    public RspVo<ReworkExamDomain> queryMyCheckDataByCondition(ReworkExamVo reworkExamVo,
                                                               ParamPage paramPage) {
        Page<ReworkExamDomain> page = new Page<ReworkExamDomain>();
        page.setPageNum(paramPage.getPage());
        page.setPageSize(paramPage.getLimit());
        //查询时，结束日期增加一天
        if (reworkExamVo.getEndDate() != null) {
            reworkExamVo.setEndDate(DateUtils.addDays(reworkExamVo.getEndDate(), 1));
        }
        //查询时，结束日期增加一天
        if (reworkExamVo.getPlanEndDate() != null) {
            reworkExamVo.setPlanEndDate(DateUtils.addDays(reworkExamVo.getPlanEndDate(), 1));
        }
        reworkExamVo.setAddBy(SessionUserUtils.getSessionUserId());
        page = reworkExamService.selectMyCheckByDomainWhere(page, reworkExamVo);
        return RspVo.getSuccessResponse(page.getTotal(), page.getResult());
    }

    /**
     * 复工审批表-新增
     * @return
     */
    @RequestMapping("/add")
    public String add(HttpServletRequest request) {
        AuthorizationVO authorizationVO = SessionUserUtils.getSessionAttributeForUserDtl();
        StaffInfo staffInfo = staffInfoService.selectByPrimaryKey(authorizationVO.getHrStaffId());
        request.setAttribute("staffName", staffInfo.getStaffName());
        //查询停工审批的记录
        StopBuild stopBuild = new StopBuild();
        stopBuild.setProcessStatus("9");
        List<StopBuild> stopBuilds = stopBuildService.selectByEntityWhere(stopBuild);
        request.setAttribute("stopBuilds", stopBuilds);
        return "ic/lay-reworkExam-add";
    }

    /**
     * 根据id查询复工审批详情  > 注意：方法命名必须为：toDealOrDetail
     * @param id 复工审批Id
     * @return
     * @see
     */
    @RequestMapping("/toDealOrDetail")
    public ModelAndView queryById(HttpServletRequest request, String id, String processDealWith) {
        Map<String, Object> map = new HashMap<String, Object>();
        ReworkExamVo reworkExamVo = reworkExamService.queryById(id);
        Map<String, Object> whereMap = Maps.newHashMap();
        whereMap.put("proCode", reworkExamVo.getProCode());
        whereMap.put("processStatus", "9");
        whereMap.put("orderCondition", "ADD_TIME desc");
        List<StopBuild> stopBuilds = stopBuildService.selectByMapWhere(whereMap);
        if (stopBuilds != null && stopBuilds.size() > 0) {
            StopBuildVo stopBuildVo = stopBuildService.queryById(stopBuilds.get(0).getId());
            reworkExamVo.setSgCoopName(stopBuildVo.getSgCoopName());
        }
        List<StartBuild> startBuilds = startBuildService.selectByMapWhere(whereMap);
        if (startBuilds != null && startBuilds.size() > 0) {
            reworkExamVo.setInnerSignFlag(startBuilds.get(0).getInnerSignFlag());
        }
        request.setAttribute("modelDetail", reworkExamVo);
        map.put("reworkExamVo", reworkExamVo);
        // 审批flag
        request.setAttribute("processDealWith", processDealWith);
        // 审批data
        processData(request, reworkExamVo.getProcessId());
        return new ModelAndView("ic/lay-reworkExam-detail", map);
    }

    /**
     * 新增复工审批
     * @return
     */
    @SuppressWarnings({"rawtypes"})
    @RequestMapping("/save")
    public @ResponseBody RspVo save(ReworkExamAssist reworkExamAssist) {

        //设计复工审批表处理
        reworkExamAssist.setHrDeptId(reworkExamAssist.getHrDeptid());
        reworkExamAssist.setHrOrgId(reworkExamAssist.getHrOrgid());
        reworkExamAssist.setStaffName(reworkExamAssist.getStaffname());
        reworkExamAssist.setHrStaffApplyId(reworkExamAssist.getHrStaffApplyid());
        String proCodeAndCodes = reworkExamAssist.getProCodeAndCodes();
        String[] split = proCodeAndCodes.split("\\_");
        reworkExamAssist.setProCode(split[0]);
        reworkExamAssist.setProName(split[2]);
        AuthorizationVO vo = SessionUserUtils.getSessionAttributeForUserDtl();
        String id = IdFactory.getUUIDUpper();
        reworkExamAssist.setId(id);
        reworkExamAssist.setAddBy(vo.getId());
        reworkExamAssist.setAddTime(top.infopub.mgr.util.DateUtils.getCurrentDateTime());
        String code = codeGeneratorConfigService.generatorCode("ic_rework_exam");
        reworkExamAssist.setCodes(code);
        // 处理processId
        reworkExamAssist.setProcessId(IdFactory.getUUIDUpper());
        reworkExamAssist.setProcessStatus("1");//审批中
        reworkExamAssist.setUptBy(vo.getId());
        reworkExamAssist.setUptTime(top.infopub.mgr.util.DateUtils.getCurrentDateTime());

        //上传附件
        List<ReworkExamAtt> reworkExamAtts = new ArrayList<ReworkExamAtt>();
        //其他附件
        String[] fileAtts1 = reworkExamAssist.getFileAtts1();
        if (fileAtts1 != null) {
            for (String file : fileAtts1) {
                ReworkExamAtt reworkExamAtt = createFileAtt(vo, id, file);
                reworkExamAtts.add(reworkExamAtt);
            }
        }
        reworkExamService.saveReworkExam(reworkExamAssist, reworkExamAtts);
        LogUtil.bizLog(LogModelType.PROJECT, AcctionType.ADD,
            "投建管理 -复工审批：项目名=" + reworkExamAssist.getProName(), null);
        return RspVo.getSuccessResponse();
    }

    private ReworkExamAtt createFileAtt(AuthorizationVO vo, String reworkId, String file) {
        //资料信息数组
        String[] fileAttStr = file.split("\\|");
        ReworkExamAtt fileAtt = new ReworkExamAtt();
        fileAtt.setId(fileAttStr[2]);
        fileAtt.setReworkId(reworkId);//项目id
        String fileName = fileAttStr[1].substring(0, fileAttStr[1].lastIndexOf("."));
        String suffix = fileAttStr[1].substring(fileAttStr[1].lastIndexOf("."),
            fileAttStr[1].length()).toLowerCase();//后缀转小写
        fileAtt.setFileName(fileName);//文件名
        fileAtt.setFileSuffix(suffix);//文件后缀
        fileAtt.setFilePath(fileAttStr[3]);//文件保存路径
        fileAtt.setAddBy(vo.getId());//添加人
        fileAtt.setAddTime(top.infopub.mgr.util.DateUtils.getCurrentDateTime());//添加时间
        return fileAtt;
    }

    /**
     * 根据id查询停工审批记录
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping("/getReworkExamById")
    @ResponseBody
    public Map<String, Object> getReworkExamById(HttpServletRequest request) {
        boolean flag = true;
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            String proCodeAndCodes = request.getParameter("proCodeAndCodes");
            String[] split = proCodeAndCodes.split("\\_");
            StopBuildVo stopBuildVo = stopBuildService.queryById(split[1]);
            Map<String, Object> whereMap = Maps.newHashMap();
            whereMap.put("proCode", stopBuildVo.getProCode());
            whereMap.put("processStatus", "9");
            whereMap.put("orderCondition", "ADD_TIME desc");
            List<BuildInfo> buildInfos = buildInfoService.selectByMapWhere(whereMap);
            if (buildInfos != null && buildInfos.size() > 0) {
                BuildInfo buildInfo = buildInfos.get(0);
                if (buildInfo != null) {
                    String id = buildInfo.getId();
                    BuildInfoDomain buildInfoDomain = buildInfoService.selectByStopBuild(id);
                    stopBuildVo.setBuildLicenceDate(buildInfoDomain.getBuildLicenceDate());
                    stopBuildVo.setBuildEndDate(buildInfoDomain.getEndDate());
                }
            }
            List<StartBuild> startBuilds = startBuildService.selectByMapWhere(whereMap);
            if (startBuilds != null && startBuilds.size() > 0) {
                stopBuildVo.setInnerSignFlag(startBuilds.get(0).getInnerSignFlag());
                stopBuildVo.setLinkPower(startBuilds.get(0).getLinkPower());
            }
            map.put("stopBuildVo", stopBuildVo);
        }
        catch (Exception e) {
            log.error("查询停工审批记录异常", e);
            flag = false;
        }
        map.put("flag", flag);
        return map;
    }

    /**
     * 上传附件
     * @param request
     * @param response
     * @return 
     * @throws IOException 
     * @see
     */
    @SuppressWarnings("rawtypes")
    @RequestMapping("/uploadAtt")
    public @ResponseBody RspVo uploadAtt(HttpServletRequest request)
        throws IOException {
        List<String> returnFileStrList = new ArrayList<>();
        MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest)request;
        Map<String, MultipartFile> map = multipartHttpServletRequest.getFileMap();
        if (map != null) {
            for (String name : map.keySet()) {
                MultipartFile file = map.get(name);
                //资料类型
                String types = request.getParameter("types");
                if (StringUtils.isEmpty(types)) {
                    return ErrorCodeEnum.ERROR_COMMON_PARAM.getRspVo("缺少参数");
                }
                if (file == null) {
                    return ErrorCodeEnum.ERROR_COMMON_PARAM.getRspVo("上传文件不能为空");
                }
                // 上传文件
                String fileId = IdFactory.getUUIDSerialNumber();
                // 服务器资源路径
                String serverPath = "reworkExamAtt";
                String filePath = FileHelper.upload(file, serverPath);
                returnFileStrList.add(types + "|" + file.getOriginalFilename().trim() + "|"
                                      + fileId + "|" + filePath);
                LogUtil.bizLog(LogModelType.PROJECT, AcctionType.ADD, "上传附件-文件名:" + filePath
                                                                      + "，文件路径:" + filePath, null);
            }
        }
        return RspVo.getSuccessResponse(returnFileStrList);
    }

}
